<template>
  <!-- <div id="map"></div> -->
  <div class="classMap" id="map">
  </div>
  <!-- 水厂点位弹窗 -->
  <dialog-component v-if="dialogVisible" @openClick="openClick" @openClose="openClose" @tabTitleClick="tabTitleClick"
    @tabClick="tabClick" :httpUrl="httpUrl" :tabsModelId="tabsModelId" :waterNameArr="waterNameArr" :videUrl="videUrl"
    :dialogVisible="dialogVisible" />

  <!-- 流量，压力，水质点位弹框 -->

  <!-- <DialogGw
  @openClick="openClick" 
  @openClose="openClose"
  :StageT="StageT"
  :StageV="StageV"
  v-if="dialogVisible1"
  >
  </DialogGw> -->
  <!-- <DiaogComponent1 
  :pointDetail="pointDetail" 
  @onClose="onClose"
  v-if="dialogVisible1" /> -->

  <DiaogComponent1 :pointDetail="pointDetail" @onClose="onClose" v-if="dialogVisible1" />
  <!-- 报警预警点位弹框 -->
  <DiaogComponent2 @openClose="openClose1" v-if="dialogVisible2" />
  <!-- 管网点位弹窗 -->
  <DyPipeNetwork
  v-if="pipeNetwork"
  @openClick="openClick" 
  @openClose="openClose" 
  @tabTitleClick="tabTitleClick"
  @tabClick="tabClick" 
  @SelectChange="SelectChange"
  :httpUrl="httpUrl"
  :tabsModelId="tabsModelId" 
  :waterNameArr="waterNameArr" 
  :videUrl="videUrl"
  :dialogVisible="dialogVisible"
  :options="options"
  :titleValue="titleValue"
  />

  <!-- 水库弹窗 -->
  <DialogSk  
  @openClick="openClick" 
  @openClose="openClose"
  :StageT="StageT"
  :StageV="StageV"
  v-if="dialogSk"></DialogSk>

  <!-- <DyPipeNetwork v-if="pipeNetwork" @openClick="openClick" @openClose="openClose" @tabTitleClick="tabTitleClick"
    @tabClick="tabClick" :httpUrl="httpUrl" :tabsModelId="tabsModelId" :waterNameArr="waterNameArr" :videUrl="videUrl"
    :dialogVisible="dialogVisible" /> -->
</template>

<script setup>
//导入相关配置信息
import { ref, onMounted, nextTick } from 'vue'
// import { fromLonLat } from 'ol/proj';
import DyBubble from '../components/DyBubble.vue'
import DialogComponent from './DyDialog.vue'
import DiaogComponent1 from './DyDialog1.vue'
import DiaogComponent2 from './DyAiarmDialog.vue'
import DyPipeNetwork from './DypipeNetwork.vue'
import DialogSk from '../components/bubblePop/dialog_Sk.vue'
// import DialogGw from '../components/bubblePop/dialog_Gw.vue'
import 'ol/css'
import XYZ from 'ol/source/XYZ' // 添加这行导入语句
// import { defaults as defaultControls, FullScreen } from 'ol/control'
// import Map from 'ol/Map'
// import View from 'ol/View'
// import TileLayer from 'ol/layer/Tile'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import { Group as LayerGroup, Vector as VectorLayer } from 'ol/layer'
import { Icon, Style, Text, Fill } from 'ol/style'
import { Vector as VectorSource } from 'ol/source'
import Tile from 'ol/layer/Tile.js'


import Map from 'ol/Map.js';
import View from 'ol/View.js';
import { defaults as defaultControls } from 'ol/control.js';
import { getWidth, getTopLeft } from 'ol/extent.js';
import TileLayer from 'ol/layer/Tile.js';
import { get as getProjection } from 'ol/proj.js';
import { fromLonLat, get } from "ol/proj";
import WMTS from 'ol/source/WMTS.js';
import WMTSTileGrid from 'ol/tilegrid/WMTS.js';


import { TileSuperMapRest } from '@supermap/iclient-ol'
import { water_factory_data } from './List/水厂点位list'
import { lngList } from './List/lng'
import { dataList } from '../components/List/压力水质流量list'
import { dataListdata } from '../components/List/原水点位'
import { Alarm } from '../components/List/报警预警'
import Overlay from 'ol/Overlay';
import bus from '../tools/eventBus'
import * as echarts from 'echarts';
import { MapLayer, IncreaseWater, IncreaseWater1, IncreaseWater2 } from '../tools/highlight-feature'
import {
  postConfiguration,
  postTrees,
  postOpenVideUrl,
  deviceMap,
  devCodeXq,
  singleDataSs,
  advancedAllList,
  dataFactoryFn,
  PostMonitorhistory
} from '../http/http'

import proj4 from 'proj4'
import { register } from "ol/proj/proj4";
import { transform } from "ol/proj";
import {proj4Epsg} from '../tools/proj4_EPSG'
import {dataSource} from '../components/List/advancedAllList'
import {water_source_data} from '../components/List/water_source'
import {getStartAndEndOfMonth,formatDate} from '../tools/timeDate' 


    const map=ref(null)

    // const mapV=ref(null)

    const markers=ref( [
        { lng: 118.674767, lat: 37.434751, iconUrl: 'icon_url_here' }, // 替换 'icon_url_here' 为图标的 URL
        // 可以添加更多的点位信息
    ])
     const dialogVisible=ref(false)
     const dialogVisible1=ref(false)
     const dialogVisible2=ref(false)
     const pipeNetwork=ref(false)
     const dialogSk=ref(false)

     const waterNameArr=ref([])
     const httpUrl=ref('')
     const videUrl=ref('')
     const tabsModelId=ref('')
     const waterNameActive=ref('')
     const pointDetail=ref([])// 监测点数据
     const typeDice=ref('')
     const bubbles=ref([])// 用于存储气泡实例
     const arrayList =ref([])// 水厂数据

     const pipeNetworkData=ref([])// 流量压力水质点位数据
     const isTrue=ref(true)
     const DataSk=ref([])
     const StageV=ref([])
     const StageT=ref([])
     // 定时器 ID
     let intervalId;
    // 管网弹窗切换实时折线图
    // 历史统计数据，设备编号---状态
    const stationKey=ref('HD72_22061_A15')
    const monitorType=ref('13')
    const stationId=ref('')
    const options=ref([])
    const activeValue=ref('')
    const titleValue=ref('')
      // 获取当前文件地址
      const pathName = window.document.location.pathname;
      var pathUrl1 = pathName.substring(0, pathName.lastIndexOf('/'));
    //  pipeNetworkFn()
     onMounted(() => {
      // FnMap()
      FnMapV()
      initMap()
      clearBubbles()
      // IncreaseWater()
      IncreaseWaterFn()
     });

// async function IncreaseWaterFn(){
// import { proj4Epsg } from '../tools/proj4_EPSG'
// import { dataSource } from '../components/List/advancedAllList'
// import { water_source_data } from '../components/List/water_source'
// // import gifler from 'gifler';


// const map = ref(null)

// // const mapV=ref(null)

// const markers = ref([
//   { lng: 118.674767, lat: 37.434751, iconUrl: 'icon_url_here' }, // 替换 'icon_url_here' 为图标的 URL
//   // 可以添加更多的点位信息
// ])
// const dialogVisible = ref(false)
// const dialogVisible1 = ref(false)
// const dialogVisible2 = ref(false)
// const pipeNetwork = ref(false)
// const waterNameArr = ref([])
// const httpUrl = ref('')
// const videUrl = ref('')
// const tabsModelId = ref('')
// const waterNameActive = ref('')
// const pointDetail = ref([])// 监测点数据
// const typeDice = ref('')
// const bubbles = ref([])// 用于存储气泡实例
// const arrayList = ref([])// 水厂数据

// const pipeNetworkData = ref([])// 流量压力水质点位数据
// const isTrue = ref(true)

// // 获取当前文件地址
// const pathName = window.document.location.pathname;
// var pathUrl1 = pathName.substring(0, pathName.lastIndexOf('/'));
// //  pipeNetworkFn()
// onMounted(() => {
//   // FnMap()
//   FnMapV()
//   initMap()
//   clearBubbles()
//   // IncreaseWater()
//   IncreaseWaterFn()
// });

async function IncreaseWaterFn() {
  arrayList.value = await dataSource({
    currPage: 1,
    geom: null,
    pageSize: 20,
    conditions: {
      waterworks: null
    }
  });
  // IncreaseWater(arrayList.value)
  // IncreaseWater2(water_source_data.features)
}
// 全国天地图-初始化地图map
function FnMap() {
  map.value = new Map({
    //1.创建地图对象 new Map()
    target: 'map', //2.绑定 div 元素
    layers: [
      //图层数组 layers
      new TileLayer({
        name: '天地图',
        source: new XYZ({
          crossOrigin: 'anonymous',
          url: 'https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=33c7090765595b5d307c40582d195454',
        }),
      }),

      new TileLayer({
        name: '注记',
        source: new XYZ({
          crossOrigin: 'anonymous',
          url: 'https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=33c7090765595b5d307c40582d195454',
        }),
      }),
    ],
    view: new View({
      //视图 View
      projection: 'EPSG:4490',
      center: [118.674767, 37.434751],
      zoom: 9,
    }),

    controls: defaultControls({
      //默认控件
      zoom: false,
      rotate: false,
      attribution: false,
      center: [118.281212, 37.557915],
    }).extend([
      //添加新控件
      // new FullScreen(),
    ]),
  })
  window.Pipe_Map = map.value;
}

var lonlat = []
// 流量/水质/压力数据
function pipeNetworkFn(list, vectorLayer1) {
  list.forEach((item) => {
    const geom = [item.x, item.y]
    // console.log(geom,'geomgeomgeomgeom');

    lonlat = proj4Epsg(geom)
    // console.log(lonlat,'lontttttttttt');

    // if(Math.floor(item.x).toString().length==6){
    // proj4.defs("EPSG:4548","+proj=tmerc +lat_0=0 +lon_0=117 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs");
    // register(proj4);
    //  lonlat=transform(geom, "EPSG:4548", "EPSG:4326")
    // }else{
    //  lonlat = proj4('EPSG:3857', 'EPSG:4326', geom) 
    // }

    if (item.dataType === 'flowmeasure') {//流量
      const b = new Feature({
        geometry: new Point(
          [lonlat[0], lonlat[1]],
          [item.gid, 'flow', item.address]
        ),
      })
      b.setStyle(hideStyleFn())
      vectorLayer1.getSource().addFeature(b)
    } else if (item.dataType === 'pressuretap') {// 压力
      const c = new Feature({
        geometry: new Point(
          [lonlat[0], lonlat[1]],
          [item.gid, 'pressure', item.address]
        ),
      })
      c.setStyle(hideStyleFn())
      vectorLayer1.getSource().addFeature(c)
    } else {
      const d = new Feature({
        geometry: new Point(
          [lonlat[0], lonlat[1]],
          [item.gid, 'waterQuality', item.address]
        ),
      })
      d.setStyle(hideStyleFn())
      vectorLayer1.getSource().addFeature(d)
    }
  })

}

// 初始化地图瓦片
function FnTile() {
  const mapLayer = new Tile({
    visible: true,
    source: new TileSuperMapRest({
      url: 'http://10.204.253.8:8090/iserver/services/map-dy20240229/rest/maps/cspmpipe_ss?prjCoordSys=%7B%22epsgCode%22:4326%7D',
      wrapX: true,
      projection: "EPSG:4326",
      crossOrigin: 'anonymous',
    }),
  })
  const mapLayer1 = new Tile({
    visible: true,
    source: new TileSuperMapRest({
      url: 'http://10.204.253.8:8090/iserver/services/map-dy20240229/rest/maps/cspmpipe_jy?prjCoordSys=%7B%22epsgCode%22:4326%7D',
      wrapX: true,
      projection: "EPSG:4326",
      crossOrigin: 'anonymous',
    }),
  })
  map.value.addLayer(mapLayer)
  map.value.addLayer(mapLayer1)
}


// 初始化地图
function FnMapV() {
  // onMounted(()=>{
  var projection = getProjection('EPSG:4326');
  // var projectionExtent = projection.getExtent();
  // console.log(projectionExtent,'projectionExtent');

  var size = getWidth([-180, -90, 180, 90]) / 256;
  var resolutions = new Array(18);
  var matrixIds = new Array(18);
  for (var z = 1; z < 19; ++z) {
    // generate resolutions and matrixIds arrays for this WMTS
    resolutions[z] = size / Math.pow(2, z);
    matrixIds[z] = z;
  }
  var webKey = '30ea4cbbb6fdfa074f70601d6cf56d38';
  var wmtsUrl_1 = 'https://service.sdmap.gov.cn/tileservice/dsfg_qsb?tk='; //矢量底图
  var wmtsUrl_2 = 'https://service.sdmap.gov.cn/tileservice/dsfg_qsb?tk='; //矢量注记

  var wmtsUrl_3 = 'https://service.sdmap.gov.cn/tileservice/sdrasterpubmap?tk='; //影像底图
  var wmtsUrl_4 = 'https://service.sdmap.gov.cn/tileservice/sdrasterpubmap?tk='; //影像注记

  var wmtsUrl_5 = 'http://t{0-7}.tianditu.gov.cn/ter_w/wmts?tk='; //地形底图
  var wmtsUrl_6 = 'http://t{0-7}.tianditu.gov.cn/cta_w/wmts?tk='; //地形注记

  var wmtsUrl_7 = 'http://t{0-7}.tianditu.gov.cn/ibo_w/wmts?tk='; //境界（省级以上）
  var wmtsUrl_8 = 'http://t{0-7}.tianditu.gov.cn/eva_w/wmts?tk='; //矢量英文注记
  var wmtsUrl_9 = 'http://t{0-7}.tianditu.gov.cn/eia_w/wmts?tk='; //影像英文注记

  map.value = new Map({
    layers: [
      new TileLayer({
        opacity: 0.7,
        source: new WMTS({
          url: wmtsUrl_1 + webKey,
          layer: '天地图山东大数据风格浅色版',  //注意每个图层这里不同
          matrixSet: 'vector',
          format: 'image/jpeg',
          style: 'default',
          projection: "EPSG:4326",
          tileGrid: new WMTSTileGrid({
            origin: getTopLeft([-180, -90, 180, 90]),
            resolutions: resolutions,
            matrixIds: matrixIds
          }),
          // wrapX: true
        })
      }),
      new TileLayer({
        opacity: 0.7,
        source: new WMTS({
          url: wmtsUrl_2 + webKey,
          layer: 'cia',   //注意每个图层这里不同
          matrixSet: 'vector',
          format: 'image/jpeg',
          style: 'default',
          projection: "EPSG:4326",
          tileGrid: new WMTSTileGrid({
            origin: getTopLeft([-180, -90, 180, 90]),
            resolutions: resolutions,
            matrixIds: matrixIds
          }),
          wrapX: true
        })
      })
    ],
    target: 'map',
    view: new View({
      center: [118.598442, 37.465866],  //东营
      projection: 'EPSG:4326',
      zoom: 11,
    }),
    controls: defaultControls({
      //默认控件
      zoom: false,
      rotate: false,
      attribution: false,
      center: fromLonLat([118.281212, 37.557915]),
    }).extend([
      //添加新控件
      // new FullScreen(),
    ]),
  });
  window.Pipe_Map = map.value
  // })
}



function clearBubbles() {
  bubbles.value.forEach(bubble => {
    map.value.removeOverlay(bubble); // 从地图上移除气泡
  });
  bubbles.value = []; // 清空气泡列表
}


function hideStyleFn() {
  // 定义显示和隐藏样式
  return new Style({
    image: new Icon({
      src: '/icon/流量监测点.png',
      scale: 0, // 缩放比例为 0，即隐藏图标
    }),
    text: new Text({
      visible: false, // 隐藏文本
    }),
  })
}


function initMap() {
  // 初始化地图栅格
  FnTile()
  // 创建一个矢量图层 VectorSource
  const vectorSource = new VectorSource()
  // 创建一个 VectorLayer，并将 VectorSource 添加到其中
  const vectorLayer = new VectorLayer({
    source: vectorSource,
  })
  // 定义墨卡托投影
  proj4.defs(
    'EPSG:3857',
    '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs'
  )
  // 定义经纬度投影
  proj4.defs('EPSG:4490', '+proj=longlat +datum=WGS84 +no_defs')
  const vectorLayer1 = MapLayer()

  //报警点位    

/// 用于存储每个 Feature 对应的 PNG 图像对象
const imageCache = new Map();

// 处理数据并更新图标
function updateIcons(data) {
  data.bllist.forEach((v) => {
    const geom = [v.geo_x, v.geo_y];
    const numberArray = geom.map(Number);
    const lonlat = proj4Epsg(numberArray);

    let feature = vectorLayer.getSource().getFeatureById(v.stationkey);
    if (!feature) {
      feature = new Feature({
        id: v.stationkey,
        geometry: new Point([lonlat[0], lonlat[1]]),
      });
      vectorLayer.getSource().addFeature(feature);
    }

    // 获取或创建 PNG 图像对象
    let image = imageCache.get(v.stationkey);
    if (!image) {
      image = new Image();
      image.src = pathUrl1 +'/icon/Bjd@3x1.png'; // 使用 PNG 图像路径
      image.onload = () => {
        imageCache.set(v.stationkey, image);
        updateFeatureStyle(feature, image, v.stationname);
      };
    } else {
      updateFeatureStyle(feature, image, v.stationname);
    }
  });
}
// gif动态方法
// function updateIcons(data) {
//   data.bllist.forEach((v) => {
//     const geom = [v.geo_x, v.geo_y];
//     const numberArray = geom.map(Number);
//     const lonlat = proj4Epsg(numberArray);

//     let feature = vectorLayer.getSource().getFeatureById(v.stationkey);
//     if (!feature) {
//       feature = new Feature({
//         id: v.stationkey,
//         geometry: new Point([lonlat[0], lonlat[1]]),
//       });
//       vectorLayer.getSource().addFeature(feature);
//     }

//     // 获取或创建 GIF 对象
//     let gif = gifCache.get(v.stationkey);
//     if (!gif) {
//       gif = gifler('/icon/Bjd@3x.gif');
//       gifCache.set(v.stationkey, gif);
//     }

//     // 处理 GIF 的每一帧
//     gif.frames(
//       document.createElement('canvas'),
//       function (ctx, frame) {
//         // const canvas = ctx.canvas;
//         // canvas.width = frame.width + 500;
//         // canvas.height = frame.height + 500;

//         // 设置图标样式并缩放图标
//         const iconStyle = new Style({
//           image: new Icon({
//             img: ctx.canvas,
//             imgSize: [frame.width, frame.height],
//             scale: 1, // 缩放比例
//             opacity: 0.8,
//           }),
//           text: new Text({
//             text: v.stationname,
//             offsetY: 20, // 调整文本位置
//             textAlign: 'center', // 文本水平居中
//             font: '10px sans-serif', // 字体样式
//             fill: new Fill({ color: 'black' }), // 文本颜色
//           }),
//         });
//              // 清除画布
//         ctx.clearRect(0, 0, frame.width, frame.height);
//         ctx.fillStyle = 'transparent'; // 可选：确保填充背景透明
//         // ctx.fillRect(0, 0, frame.width, frame.height);
//         ctx.drawImage(frame.buffer, 0, 0);
//         feature.setStyle(iconStyle);
//       },
//       true
//     );
//   });
// }


// 更新 Feature 样式
function updateFeatureStyle(feature, image, stationName) {
  const iconStyle = new Style({
    image: new Icon({
      img: image,
      imgSize: [image.width, image.height],
      scale: 0.3, // 缩放比例
      opacity: 0.8,
    }),
    text: new Text({
      text: stationName,
      offsetY: 20, // 调整文本位置
      textAlign: 'center', // 文本水平居中
      font: 'bold  10px sans-serif', // 字体样式
      fill: new Fill({ color: 'black' }), // 文本颜色
    }),
  });
  feature.setStyle(iconStyle);
}

// 示例：监听数据更新
bus.on('bjlist', (data) => {
  updateIcons(data);
});

  // 将图层添加到地图
  map.value.addLayer(vectorLayer);

  // 添加地图点击事件监听器
  map.value.on('click', function (evt) {
    // 获取点击位置的像素
    var pixel = map.value.getEventPixel(evt.originalEvent);

    // 遍历点击位置的要素（图标）
    map.value.forEachFeatureAtPixel(pixel, function (feature) {
      // 获取点击的图标（feature）的属性
      var properties = feature.getProperties();

      // 检查是否是目标图标
      if (properties.id === Alarm.warning.stationkey) {
        // 执行特定的操作
        console.log('Clicked on specific feature:', properties);
        // 示例：显示一个弹出框或执行其他操作
      } else {
        bus.emit('Tablealve', {
          revriced: properties,

        }),
          console.log('Clicked on another feature:', properties);
        dialogVisible2.value = true

      }
    });
  });
  const qq = dataSource({
    geom: null,
    conditions: {
      waterparticle: null,
      pressuretap: null,
      flowmeasure: null
    }
  })
  // IncreaseWater1()
  advancedAllList({
    geom: null,
    conditions: {
      waterparticle: null,
      pressuretap: null,
      flowmeasure: null
    }
  }).then((res) => {
    if (res.status == '200') {
      pipeNetworkFn(res.data.returnValue.result, vectorLayer1)
    }
  })

  // 流量点位
  // dataList.Flow.forEach((item) => {
  //     lonlat = proj4('EPSG:3857', 'EPSG:4490', [
  //       +item.datamapx,
  //       +item.datamapy,
  //     ])
  //     const b = new Feature({
  //       geometry: new Point(
  //         [lonlat[0], lonlat[1]],
  //         [item.devicecode, 'flow', item.datapointname]
  //       ),
  //     })
  //     b.setStyle(hideStyle)
  //     vectorLayer1.getSource().addFeature(b)
  //   })
  // // 压力点位
  // dataList.Pressure.forEach((item) => {
  //     lonlat = proj4('EPSG:3857', 'EPSG:4490', [
  //       +item.datamapx,
  //       +item.datamapy,
  //     ])
  //     const c = new Feature({
  //       geometry: new Point(
  //         [lonlat[0], lonlat[1]],
  //         [item.devicecode, 'pressure', item.datapointname]
  //       ),
  //     })
  //     c.setStyle(hideStyle)
  //     vectorLayer1.getSource().addFeature(c)
  //   })
  //   // 水质点位
  // console.log(pipeNetworkData.value,'pipeNetworkData.value');

  // pipeNetworkData.value.forEach((item) => {
  //   const geom=item.geom.coordinates
  //   lonlat = proj4('EPSG:3857', 'EPSG:4490', [
  //       +geom[0],
  //       +geom[1],
  //     ])
  //     console.log(lonlat[0], lonlat[1],'lonlat[0], lonlat[1]');

  //     const d = new Feature({
  //       geometry: new Point(
  //         [lonlat[0], lonlat[1]],
  //         [item.gid, 'waterQuality', item.sourcetype]
  //       ),
  //     })
  //     d.setStyle(hideStyle)
  //     vectorLayer1.getSource().addFeature(d)
  //   })

  map.value.on('singleclick', (evt) => {
    if (map.value.hasFeatureAtPixel(evt.pixel)) {
      const feature = map.value.getFeaturesAtPixel(evt.pixel)
      var aa = ''
      var bb = ''
      var cc = ''

      aa = feature[0].values_.geometry.layout
      bb = feature[0].values_.geometry.layout[1]
      cc = feature[0].values_.geometry.layout
      console.log(aa,'aaaa');
      titleValue.value=aa[2]
      
      if (aa[1] === 'waterPlant') {
        let id = feature[0].values_.geometry.layout[0]
        waterNameActive.value = feature[0].values_.geometry.layout[2]
        dialogVisible.value = true
        postConfiguration({ configurationId: id }).then((res) => {
          httpUrl.value = res.data
        })
      } else if (
        bb === 'flow' ||
        bb === 'pressure' ||
        bb === 'waterQuality'
      ) {
        dialogVisible1.value = true
        let deviceCode = feature[0].values_.geometry.layout[0]
        singleDataSs({ deviceCode }).then((res) => {
          pointDetail.value = res.data
        })
      }
      else if(aa[1]=='waterparticle' || aa[1]=='pressuretap' || aa[1]=='flowmeasure'){
        // 一定级别显示管网数据
        pipeNetwork.value = true
    
        console.log(aa[1],aa[0].archiveid,'bbbb');

        if(aa[1]=='waterparticle'){
           options.value=[
              {value: 'Zd',label: '浊度',},
              {value: 'Yl',label: '余氯',},
              {value: 'Ph',label: 'ph',}]
            monitorType.value="13"
            // activeValue.value='Zd'
            stationId.value=aa[0].archiveid
            stationKey.value=stationId.value+'_A15'
            startMonitoring();
        }else if(aa[1]=='pressuretap' || aa[1]=='flowmeasure'){

           // 需要提取的元素
           monitorType.value="1"
          //  activeValue.value='Zd'
           stationId.value=aa[0].archiveid
           stationKey.value=stationId.value
          //  const monititems='P1:正向累计,P2:反向累计,A1:瞬时,A5:压力'
           const a= aa[0].monititems.split(',')
          const b= a.filter((item)=>item.split(':')[1]=='压力' || item.split(':')[1]=='瞬时'|| item.split(':')[1]=='瞬时流量')
          const c=b.map((item)=>{
            return {
              value:item.split(':')[0],
              label:item.split(':')[1]
            }
          })
          options.value=c
          stationId.value=aa[0].archiveid
          startMonitoring();
        }
      }
      else if(cc[2]=='Sk'){
        // 水库历史数据
        dialogSk.value=true
        dataFactory(cc[1])
        

        // })
      }
    } else {
      console.log('点击的像素点上没有要素')
    }
  })



  // 监听地图的缩放事件
  // map.value.on('moveend', () => {
  //   let zoom = map.value.getView().getZoom()

  //   let vectorSource = vectorLayer1.getSource()
  //   let features = vectorSource.getFeatures()

  //   if (zoom >= 15) {
  //     features.forEach((feature) => {
  //       // 流量监测点icon样式
  //       if (feature.values_.geometry.layout[1] === 'flow') {
  //         feature.setStyle(
  //           new Style({
  //             image: new Icon({
  //               src: pathUrl1+'/icon/Lljcd@3x.png',
  //               scale: 0.3, // 显示图标
  //             }),
  //             text: new Text({
  //               text: feature.values_.geometry.layout[2], // 需要显示的文本内容
  //               offsetY: 20, // 调整文本位置，使其显示在图标下方
  //               textAlign: 'center',
  //               font: '10px sans-serif',
  //               fill: new Fill({ color: 'black' }),
  //             }),
  //           })
  //         )
  //       }
  //       // 压力监测点icon样式
  //       if (feature.values_.geometry.layout[1] === 'pressure') {
  //         feature.setStyle(
  //           new Style({
  //             image: new Icon({
  //               src: pathUrl1+ '/icon/Yljcd@3x.png',
  //               scale: 0.3, // 显示图标
  //             }),
  //             text: new Text({
  //               text: feature.values_.geometry.layout[2], // 需要显示的文本内容
  //               offsetY: 20, // 调整文本位置，使其显示在图标下方
  //               textAlign: 'center',
  //               font: '10px sans-serif',
  //               fill: new Fill({ color: 'black' }),
  //             }),
  //           })
  //         )
  //       }

  //       // 水质监测点icon样式
  //       if (feature.values_.geometry.layout[1] === 'waterQuality') {
  //         feature.setStyle(
  //           new Style({
  //             image: new Icon({
  //               src: pathUrl1+'/icon/Szjcd@3x.png',
  //               scale: 0.3, // 显示图标
  //             }),
  //             text: new Text({
  //               text: feature.values_.geometry.layout[2], // 需要显示的文本内容
  //               offsetY: 20, // 调整文本位置，使其显示在图标下方
  //               textAlign: 'center',
  //               font: '10px sans-serif',
  //               fill: new Fill({ color: 'black' }),
  //             }),
  //           })
  //         )
  //       }
  //     })
  //   } else {
  //     // 当地图缩放级别小于10时隐藏要素
  //     features.forEach((feature) => {
  //       if (
  //         feature.values_.geometry.layout[1] === 'flow' ||
  //         feature.values_.geometry.layout[1] === 'pressure' ||
  //         feature.values_.geometry.layout[1] === 'waterQuality'
  //       ) {
  //         feature.setStyle(hideStyleFn())
  //       }
  //     })
  //   }
  // })
}

// 定时更新数据，5分钟为300000毫秒
const updateInterval = 1 * 60 * 1000; // 5分钟

// 调用这个函数来启动定时更新
function startMonitoring() {
  MonitorHistory(); // 首次加载
  intervalId= setInterval(() => {
    console.log('一分钟加载一次');
    MonitorHistory(); // 之后每5分钟加载一次数据
  }, updateInterval);
}


// 管网弹窗选择器切换事件
function SelectChange(value){
  // console.log(value,'ffsdsdds');
  switch(value){
    case "Zd" :
    stationKey.value=stationId.value+'_A15'
    monitorType.value="13"
      break;
      case "Yl" :
    stationKey.value=stationId.value+'_A13'
    monitorType.value="12"
      break;
      case "Ph" :
    stationKey.value=stationId.value+'_A14'
    monitorType.value="14"
      break;
    case "A1" :
    stationKey.value=stationId.value
    monitorType.value="1"
      break;
      case "A5" :
    stationKey.value=stationId.value+'_A5'
    monitorType.value="2"
      break;
  }

  MonitorHistory()
}

// 流量-数据不需要点位标识符


// 历史数据入参
function MonitorHistoryValue(){
  const today=new Date()
  return {
    "startTime":formatDate(today),
    "endTime":formatDate(today),
    "stationKey":stationKey.value,
    "monitorType":monitorType.value
  }
}
const HistoryData=ref([])

// 历史数据源
function MonitorHistory(){
 
 PostMonitorhistory(MonitorHistoryValue()).then((res)=>{
    if(res.status===200){
     const dataHistory=res.data.returnValue.result
     console.log('dataHistory',dataHistory);
    //  HistoryData.value=dataHistory
     PipelineLine(dataHistory)
    }

    
 })
}
// 转换数据格式
function formatData(data) {
  return data.map(item => ({
    name: item.date,
    value: [
      new Date(item.date).getTime(), // 时间戳
      parseFloat(item.value) // 数值
    ]
  }));
}

// 管网折线图

function PipelineLine(data1){


nextTick(()=>{ // 要放在对响应式数据修改之后          
            var chartDom = document.getElementById('main5');
            var myChart = echarts.init(chartDom);
            var option;
            let data = formatData(data1);
              option = {
              tooltip: {
              trigger: 'axis',
              formatter: function (params) {
                params = params[0];
                var date = new Date(params.value[0]);
                var hours = date.getHours().toString().padStart(2, '0');
                var minutes = date.getMinutes().toString().padStart(2, '0');
                return (
                date.getFullYear() +'/' + 
                  date.getDate() +
                  '/' +
                  (date.getMonth() + 1) +
                  '  ' +
                  hours+':'+minutes+'  '
                  +
                  params.value[1]
                );
              },
              axisPointer: {
                animation: false
              }
            },
            xAxis: {
              type: 'time',
              splitLine: {
                show: false
              }
            },
            yAxis: {
              name:yAxisUnit(),
              type: 'value',
              boundaryGap: [0, '100%'],
              splitLine: {
                show: false
              }
            },
            series: [
              {
                name: 'pH值',
                type: 'line',
                showSymbol: false,
                data: data
              }
            ]
};
             option && myChart.setOption(option);
})
      
      
}


// 弹窗单位
function yAxisUnit(){
  switch(monitorType.value){
    case '1':// 流量
    return 'm³/h'
    break;
    case '2':// 压力
    return 'MPa'
    break;
    case '13':// 浊度
    return 'NTU'
    break;
    case '12':// 余氯
    return 'mg/L'
    break;
  }
}


function dataFactoryValue(){
    // const today=new Date()
    // const yesterday=new Date(today)
    // yesterday.setDate(today.getDate()-1)
    return {
    datasetId:'30d15a8a-c551-c286-57bc-320c6dad36c5',
    dataTime_start:getStartAndEndOfMonth().start,
    dataTime_end: getStartAndEndOfMonth().end
   }
  }

  // 查询-起止时间水库信息数据接口（到昨日）
  function dataFactory(name){
    console.log('data',name);
  const formDataValue = new URLSearchParams(dataFactoryValue()).toString();
    //  console.log(name1,name2,'ffff');
    dataFactoryFn(formDataValue).then((res)=>{
    const data=res.data
    if(data.code=='200'){
      // console.log(data.data,'ddddd');
      const DataSk1= data.data.filter((item)=>item.sk_name==name)
      FoldLineData(DataSk1)
    //  console.log(DataSk.value,'ffff');
     
    }
    })
}

// 水库弹窗折线图展示历史数据
function FoldLineData(data){
    //  const Rq = data.map(item => item.rq);
     data.sort((a, b) => new Date(a.rq) - new Date(b.rq)); // 按日期排序
     const Rq = data.map(item => item.rq); // 提取排序后的日期
     const Sw = data.map(item => item.sw);
     const Kc = data.map(item => item.kc);
     nextTick(()=>{
      var chartDom = document.getElementById('SkBox');
      var myChart = echarts.init(chartDom);
      var option;
      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          // formatter: function (params) {
          //   let tooltipContent = '';
          //   params.forEach(item => {
          //     tooltipContent += `${item.seriesName}: ${item.data} ${item.seriesName === '水位' ? 'm' : 'SKU'}<br>`;
          //   });
          //   return tooltipContent;
          // },
          },
          legend: {
            data: ['水位', '库存']
          },
          toolbox: {
            show: true,
            feature: {
              saveAsImage: {
                show: false // 隐藏下载图标
              }
            }
          },
          xAxis: {
           type: 'category',
           boundaryGap: false,
             data:Rq
          },  
          yAxis: {
            type: 'value',
              nameGap: 16,
              axisLabel: {
                formatter: '{value} m' // 水位单位
              },
              axisLabel: {
                      formatter: function (value) {
                          // 将数值转换为万为单位
                          if (value >= 10000 || value <= -10000) {
                              return (value / 10000).toFixed(0) + '万';
                          }
                          return value;
                      }
                  }
            },
            series: [
              {
                type: 'line',
                data: Sw,
                name:'水位'
              },
              {
                type: 'line',
                data:Kc,
                name:'库存'
              }
            ]
          };
          option && myChart.setOption(option);
        })
}

//111
function tabClick(value) {
  let pid = value.props.name.split('_')[1]
  postOpenVide(pid)
}
function tabTitleClick(e) {
  if (e.props.name === '2') {
    postTrees().then((res) => {
      let luChen = res.data?.[0]?.[0]
      let luXing = res.data?.[0]?.[1]
      let luChenList = luChen.children?.[0]?.children
      let luXingList = luXing.children
      console.log('luChenList', luChenList);

      // 初始化为空
      const waterArr = []
      luChenList.forEach((item) => {
        if (
          item.alias &&
          waterNameActive.value == item.alias.split('-')[0]
        ) {
          // alert('11')
          waterArr.push(item)
          waterNameArr.value = waterArr
          tabsModelId.value = waterArr[0].id
          postOpenVide(waterArr[0].id.split('_')[1])
        }
      })
      luXingList.forEach((it) => {
        it.children.forEach((item) => {
          if (
            item.alias &&
            waterNameActive.value == item.alias.split('-')[0]
          ) {
            if (
              item.alias &&
              waterNameActive.value == item.alias.split('-')[0]
            ) {
              waterNameArr.value.push(item)
            }
          }
        })
      })
    })
  }
}
//视频监控接口
function postOpenVide(pid) {
  postOpenVideUrl({
    origin: 'http://10.204.253.2',
    channelIdQueryList: [pid],
  }).then((res) => {
    let url = res.data[0][0]?.playUrl
    videUrl.value = url
    console.log(videUrl.value, 'videUrl.value');

  })
}
function openClick() {
  editableTabsValue.value = '1'
}
// 关闭弹窗清除数据
function openClose() {
  dialogVisible.value = false
  pipeNetwork.value = false
  // waterNameArr.value= []
  // httpUrl.value = ''
  // videUrl.value = ''
  console.log('触发');
  stopMonitoring()
  
}

// 停止定时器
function stopMonitoring() {
  clearInterval(intervalId);
  console.log('定时器已停止');
}
// 详情数据关闭
function onClose() {
  dialogVisible1.value = false
}
// 详情数据关闭
function openClose1() {
  dialogVisible2.value = false
}


</script>

<style>
.classMap {
  position: relative;
}

#map {
  height: 100vh;
  width: 100vw;
}

#mapW {
  height: 100vh;
  width: 98vw;
  margin-left: 14px;
}

.custom-bubble {
  position: absolute;
  /* background-color: white; */
  /* box-shadow: 0 1px 4px rgba(0,0,0,0.2); */
  padding: 15px;
  border-radius: 10px;
  /* border: 1px solid #cccccc; */
  bottom: 12px;
  left: -50px;
  min-width: 160px;
  font-size: 10px;
  background-image: url('/public/icon/气泡背景@3x.png');
  background-size: cover;
  /* 使背景图片覆盖整个元素 */
  background-position: center;
  /* 使背景图片居中 */
  background-repeat: no-repeat;
  /* 避免背景图片重复 */
}

.custom-bubble:after,
.custom-bubble:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.custom-bubble:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.custom-bubble:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}
::v-deep.el-dialog__headerbtn{
  z-index: 99 !important
}
</style>
